import os, sys

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)
DEFAULT_CONFIG_PATH = "%s/conf" % APPLICATION_INSTALL_DIR

from amara import binderytools

from zope.interface import implements

from watcher.exceptions import WatcherConfigError
from watcher.interfaces import IConfigLoader

class ConfigLoader(object):
    """the idea is to be able to instantiate this against a directory
       and then call cl.load(config)
       >>> cl = ConfigLoader('../definitions/')
       >>> cl.load("watch_template")
    """
    implements(IConfigLoader)
    def __init__(self, configdir=None):
        self.configdir = configdir.strip()
        if self.configdir is None:
            self.configdir = DEFAULT_CONFIG_PATH 
        if not os.path.isdir(self.configdir):
            raise WatcherConfigError("directory |%s| is not valid!" % self.configdir)

    def load(self, name):
        name = name.strip()
        # try filepath at the configDir we're handed.
        # if it's not there, try the default.
        # if default is not there, raise
        filepath = os.path.join(self.configdir, "%s.xml" % name)
        if not os.path.isfile(filepath.strip()):
            filepath = os.path.join(DEFAULT_CONFIG_PATH, "%s.xml" % name)
            if not os.path.isfile(filepath.strip()):
                raise WatcherConfigError("filename %s in configdir %s is not valid!" % (name, self.configdir))
        configDoc = binderytools.bind_file(filepath)
        # we don't need to index the config like
        # classinstance.config.classname.attrs.attribute
        # instead
        # classinstance.config.attrs.attribute
        return configDoc.childNodes[0]

